package org.benxiong.iplay.service;

import org.benxiong.iplay.ui.component.UrlImageView;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;

public class ImageDownloder {

	public static void downloadImageForImageView(UrlImageView imageView) {
		AsyncHttpClient client = new AsyncHttpClient();
		String[] allowedTypes = new String[] { "image/jpeg" };
		final String urlKey = imageView.getUrl();
		final UrlImageView target = imageView;
		
		client.get(urlKey, new BinaryHttpResponseHandler(allowedTypes) {
			@Override
			public void onSuccess(byte[] imageData) {
				// Successfully got a response
				Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
				CacheService.addBitmapToCache(urlKey, bitmap, true);
				target.setImageBitmap(bitmap);
				target.setLoaded(true);
			}

			@Override
			public void onFailure(Throwable e, byte[] imageData) {
				// Response failed :(
				int rest = target.getNumOfRetry() - target.getCountOfRetry();
				if (rest > 0) {
					ImageDownloder.downloadImageForImageView(target);
				}
				
				target.setCountOfRetry(target.getCountOfRetry() + 1);
			}
		});
	}
}
